import ResourceCard from '@/components/ResourceCard';
import { getLinks, getTags } from '@/services/ant-design-pro/links';
import { RiseOutlined, TagsOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, Form, List, Radio, Select } from 'antd';
import React from 'react';
import { useState } from 'react';
import { useEffect } from 'react';
import styles from './index.less';
const { Option } = Select;

const listGrid = {
  gutter: 16,
  xs: 1,
  sm: 1,
  md: 2,
  lg: 2,
  xl: 3,
  xxl: 3,
};

const formItemLayout = {
  labelCol: {
    sm: {
      span: 4,
    },
    lg: {
      span: 3,
    },
    xl: {
      span: 2,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
  },
};

const tags = [];
const res = await getTags();
const temp = res.data;
for (let i = 0; i < temp.length; i++) {
  tags.push(<Option key={temp[i]?.id}>{temp[i]?.tip}</Option>);
}

function compare(p) {
  //这是比较函数
  return function (m, n) {
    var a = m[p];
    var b = n[p];
    return a - b; //升序
  };
}

const Resources = () => {
  const [resources, setResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [filter, setFilter] = useState('');
  //   const [loading, setLoading] = useState < Boolean > [true];

  useEffect(() => {
    if (loading === false) {
      requestLinks();
      setLoading(true);
    }
  }, [resources]);

  // 请求所有资源
  const requestLinks = async (values) => {
    try {
      const res = await getLinks({ ...values });
      if (res.data !== resources) {
        setResources(res.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 表单变化进行筛选
  const onValuesChange = (changedValues, allValues) => {
    const tempFilter = { ...allValues };
    // setFilter(tmpFilter);
    filterResources(tempFilter);
  };

  const filterResources = async (tempFilter) => {
    setResources([]);
    console.log(tempFilter);
    let res = [];
    if (tempFilter.tags === undefined || tempFilter.tags.length === 0) {
      res = await getLinks();
    } else {
      let tips = tempFilter.tags.map(Number);
      const values = {
        tip: tips,
      };
      res = await getLinks({ ...values });
    }

    let temp = res.data;
    if (tempFilter.orderKey === 'time') {
      temp.sort(compare('uploadTime'));
      setResources(temp);
    } else if (tempFilter.orderKey === 'star') {
      temp.sort(compare('start'));
      setResources(temp);
    } else if (tempFilter.orderKey === 'mark') {
      temp.sort(compare('bookmarkCnt'));
      setResources(temp);
    }
    console.log(temp);
    setResources(temp);
  };

  // 对资源进行排序
  const sortResources = (e) => {
    setResources([]);
    let temp = resources;
    console.log(temp);
    if (e === 'time') {
      temp.sort(compare('uploadTime'));
      setResources(temp);
    } else if (e === 'star') {
      temp.sort(compare('start'));
      setResources(temp);
    } else if (e === 'mark') {
      temp.sort(compare('bookmarkCnt'));
      setResources(temp);
    } else {
      requestLinks();
    }
    console.log(temp);
  };

  return (
    <div className={styles.filterCardList} style={{ width: '100%' }}>
      {/* 页面容器 */}
      <PageContainer>
        {/* 页面上方的筛选框 */}
        <Card bordered={false}>
          <Form
            {...formItemLayout}
            form={form}
            onValuesChange={onValuesChange}
            // initialValues={{
            //   orderKey: '_createTime',
            //   ...searchParams,
            // }}
            labelAlign="left"
          >
            <Form.Item
              label={
                <>
                  <TagsOutlined /> <span style={{ marginLeft: 8 }}>筛选</span>
                </>
              }
              name="tags"
              labelAlign="left"
            >
              <Select
                mode="multiple"
                allowClear
                style={{
                  width: '100%',
                }}
                filterOption={false}
              >
                {tags}
              </Select>
            </Form.Item>
            <Form.Item
              label={
                <>
                  <RiseOutlined /> <span style={{ marginLeft: 8 }}>排序</span>
                </>
              }
              name="orderKey"
            >
              <Radio.Group defaultValue="default">
                <Radio.Button value="default">综合</Radio.Button>
                <Radio.Button value="time">时间</Radio.Button>
                <Radio.Button value="star">评价</Radio.Button>
                <Radio.Button value="mark">收藏</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Form>
        </Card>
        {/* 资源列表 */}
        <List
          rowKey="id"
          itemLayout="horizontal"
          dataSource={resources}
          // loading={loading}
          grid={listGrid}
          renderItem={(item) => {
            return (
              <List.Item key={item.id}>
                <ResourceCard
                  resourceId={item.id}
                  // loading={loading}
                  // prePageState={searchParams}
                  // keyword={searchParams.name}
                />
              </List.Item>
            );
          }}
        />
      </PageContainer>
    </div>
  );
};

export default Resources;
